#include "audio.h"
#include "ui_audio.h"
#include<QAudioOutput>
#include<QFileDialog>
#include<QMessageBox>
Audio::Audio(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Audio)
{
    ui->setupUi(this);
    player = new QMediaPlayer(this);
    playlist = new QMediaPlaylist(this),  // 初始化播放列表
    player->setPlaylist(playlist);

    ui->playButton->setEnabled(false);
    connect(player, &QMediaPlayer::positionChanged, this, &Audio::updatePosition);

    player->setVolume(50);  // 默认50%音量
    ui->horizontalSlider_2->setValue(50);
       // 连接音量控制信号
    connect(ui->horizontalSlider_2, &QSlider::valueChanged, player, &QMediaPlayer::setVolume);

}

Audio::~Audio()
{
    delete ui;
}

void Audio::on_addButton_clicked()
{
    QStringList files = QFileDialog::getOpenFileNames(
            this,
            "选择音乐文件",
            QDir::homePath(),
            "音频文件 (*.mp3 *.wav *.ogg *.flac);;所有文件 (*.*)");

        if (!files.isEmpty()) {
            foreach (QString file, files) {
                playlist->addMedia(QUrl::fromLocalFile(file));
            }

            if (!currentFile.isEmpty()) {
                playlist->setCurrentIndex(0);
            }

            ui->playButton->setEnabled(true);
            currentFile = files.first();

            // 显示当前播放文件名
            QFileInfo fileInfo(currentFile);
            ui->currentSongLabel->setText("当前: " + fileInfo.fileName());
            player->setPlaylist(playlist);
        }
}
void Audio::on_playButton_clicked()
{
    if (player->mediaStatus() == QMediaPlayer::NoMedia) {
        QMessageBox::warning(this, "警告", "请先添加音频文件");
        return;
    }

    if (player->state() == QMediaPlayer::PlayingState) {
        player->pause();
        ui->playButton->setText("播放");
    } else {
        // 确保音频输出已设置

        player->play();
        ui->playButton->setText("暂停");
    }
}
void Audio::updatePosition(qint64 position)
{
    // 获取音频总时长（毫秒）
    const qint64 totalDuration = player->duration();

    // 确保分母不为零（避免除零错误）
    if (totalDuration <= 0) return;

    // 计算并设置进度条位置（0-100范围）
    ui->horizontalSlider->setValue(static_cast<int>((position * 100) / totalDuration));

    // 格式化当前播放时间（mm:ss）
    const QTime currentTime = QTime(0, 0).addMSecs(position);
    ui->label_2->setText(currentTime.toString("mm:ss"));

    // 格式化总时长（mm:ss）
    const QTime durationTime = QTime(0, 0).addMSecs(totalDuration);
    ui->label_3->setText(durationTime.toString("mm:ss"));
}

void Audio::on_pushButton_4_clicked()
{
    emit showMenu();
}
